Package-level declarations

Types

Link copied to clipboard

Mutable abort source — the v6 equivalent of AbortController. Hold the controller, hand the signal to the agent, call abort from the UI's stop button.

Link copied to clipboard
class AbortError(message: String = "operation aborted") : CancellationException

Thrown from AbortSignal.throwIfAborted when the signal has fired.

Link copied to clipboard
interface AbortSignal

Cancellation primitive matching the Vercel AI SDK v6 AbortSignal shape.

Link copied to clipboard
interface Agent<TContext, TOutput>

The agent contract — what application code depends on (best practice #7). ToolLoopAgent is the default implementation, but other implementations exist (e.g. a DurableAgent that journals to disk for offline-resilient mode, a SubagentTestAgent that records calls for unit tests).

Link copied to clipboard
data class AgentCallHooks(val onStart: suspend (OnStartEvent) -> Unit? = null, val onStepStart: suspend (OnStepStartEvent) -> Unit? = null, val onStepFinish: suspend (OnStepFinishEvent) -> Unit? = null, val onFinish: suspend (OnFinishEvent) -> Unit? = null, val onError: suspend (OnErrorEvent) -> Unit? = null, val onChunk: suspend (OnChunkEvent) -> Unit? = null, val onAbort: suspend (OnAbortEvent) -> Unit? = null, val experimental_onToolCallStart: suspend (OnToolCallStartEvent) -> Unit? = null, val experimental_onToolCallFinish: suspend (OnToolCallFinishEvent) -> Unit? = null)

Per-call lifecycle hooks. These mirror the ones on the agent constructor but apply to a single Agent.generate / Agent.stream invocation — useful for request-scoped logging, tracing, or progress UI.

Link copied to clipboard

Tool-loop error taxonomy (Phase 4C gap #25). The agent loop's failure modes were previously all String messages on StreamEvent.Error / StreamEvent.ToolError; catch sites had no way to discriminate "model called an unknown tool" from "executor threw" from "input decode failed" without parsing the message.

Link copied to clipboard
class AgentSession<TContext, TOutput>(scope: CoroutineScope, agent: Agent<TContext, TOutput>, initialMessages: List<ModelMessage> = emptyList())
Link copied to clipboard
data class AgentSessionState<TOutput>(val messages: List<ModelMessage> = emptyList(), val status: AgentSessionStatus = AgentSessionStatus.Ready, val text: String = "", val output: TOutput? = null, val pendingApprovals: List<PendingApproval> = emptyList(), val lastResult: GenerateResult<TOutput>? = null, val error: Throwable? = null)
Link copied to clipboard
data class AgentSettings<TContext>(val instructions: String? = null, val model: LanguageModel? = null, val tools: ToolSet<TContext>? = null, val activeTools: List<String>? = null, val providerOptions: Map<String, JsonElement>? = null, val temperature: Float? = null, val topP: Float? = null, val topK: Int? = null, val maxOutputTokens: Int? = null, val stopSequences: List<String>? = null, val seed: Int? = null, val presencePenalty: Float? = null, val frequencyPenalty: Float? = null, val responseFormat: ResponseFormat? = null)

Returned from prepareCall. Any non-null field overrides the agent default for this invocation only.

Link copied to clipboard
annotation class AiSdkDsl

Marks AI SDK builder receivers so nested DSL blocks don't leak outer scopes.

Link copied to clipboard
Link copied to clipboard
open class AiSdkException(message: String, cause: Throwable? = null) : RuntimeException
Link copied to clipboard
class APICallError(message: String, val url: String, val requestBodyValues: Any? = null, val statusCode: Int? = null, val responseHeaders: Map<String, String>? = null, val responseBody: String? = null, cause: Throwable? = null, val isRetryable: Boolean = statusCode == 408 || statusCode == 409 || statusCode == 429 || (statusCode ?: 0) >= 500, val data: Any? = null) : AiSdkException
Link copied to clipboard
data class AudioSource(val mediaType: String, val base64: String, val filename: String? = null)
Link copied to clipboard
data class AuthOptions(val serverUrl: String, val authorizationCode: String? = null, val callbackState: String? = null, val scope: String? = null, val resourceMetadataUrl: String? = null, val client: HttpClient? = null)
Link copied to clipboard
@Serializable
data class AuthorizationServerMetadata(val issuer: String? = null, val authorizationEndpoint: String? = null, val tokenEndpoint: String? = null, val registrationEndpoint: String? = null, val responseTypesSupported: List<String>? = null, val grantTypesSupported: List<String>? = null, val tokenEndpointAuthMethodsSupported: List<String>? = null, val codeChallengeMethodsSupported: List<String>? = null)
Link copied to clipboard
Link copied to clipboard
data class CallCompletionApiOptions(val api: String = "/api/completion", val id: String = generateId("completion"), val prompt: String, val headers: Map<String, String> = emptyMap(), val body: Map<String, JsonElement> = emptyMap(), val streamProtocol: CompletionStreamProtocol = CompletionStreamProtocol.Data, val transport: CompletionTransport, val abortSignal: AbortSignal = AbortSignalNever, val setCompletion: (String) -> Unit = {}, val setLoading: (Boolean) -> Unit = {}, val setError: (Throwable?) -> Unit = {}, val onFinish: suspend (prompt: String, completion: String) -> Unit = { _, _ -> }, val onError: suspend (Throwable) -> Unit = {})
Link copied to clipboard
data class CallSettings(val temperature: Float? = null, val topP: Float? = null, val topK: Int? = null, val maxOutputTokens: Int? = null, val stopSequences: List<String>? = null, val seed: Int? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val abortSignal: AbortSignal? = null, val presencePenalty: Float? = null, val frequencyPenalty: Float? = null, val responseFormat: ResponseFormat? = null)
Link copied to clipboard
Link copied to clipboard
@Serializable
data class CallToolResult(val content: List<JsonObject> = emptyList(), val structuredContent: JsonElement? = null, val isError: Boolean = false, val toolResult: JsonElement? = null, val meta: JsonObject? = null)
Link copied to clipboard
@Serializable
data class CallWarning(val type: String, val message: String? = null, val details: JsonElement? = null)

Provider warning for a call that still completed. Mirrors v6's CallWarning shape without baking provider-specific warning enums into common code.

Link copied to clipboard
sealed interface ChunkBy

Smooths text/reasoning streaming output by buffering until a chunk boundary, then releasing complete chunks with a configurable delay.

Link copied to clipboard
class Completion(options: UseCompletionOptions = UseCompletionOptions())
Link copied to clipboard
data class CompletionRequest(val api: String, val id: String, val prompt: String, val headers: Map<String, String> = emptyMap(), val body: Map<String, JsonElement> = emptyMap(), val streamProtocol: CompletionStreamProtocol = CompletionStreamProtocol.Data, val abortSignal: AbortSignal = AbortSignalNever)
Link copied to clipboard
data class CompletionRequestOptions(val headers: Map<String, String> = emptyMap(), val body: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
Link copied to clipboard
@Serializable
data class Configuration(val name: String, val version: String, val title: String? = null)
Link copied to clipboard
@Serializable
sealed interface ContentPart

Content part of a ModelMessage. Sealed so consumers exhaust over variants — adding a new content type forces a compile error at every dispatch site.

Link copied to clipboard
data class CustomProvider(val providerId: String, languageModels: Map<String, LanguageModel> = emptyMap(), embeddingModels: Map<String, EmbeddingModel> = emptyMap(), imageModels: Map<String, ImageModel> = emptyMap(), speechModels: Map<String, SpeechModel> = emptyMap(), transcriptionModels: Map<String, TranscriptionModel> = emptyMap(), rerankingModels: Map<String, RerankingModel> = emptyMap(), videoModels: Map<String, VideoModel> = emptyMap(), fallbackProvider: Provider? = null) : Provider
Link copied to clipboard
data class DataUrl(val mediaType: String, val base64: String)
Link copied to clipboard
data class DeepPartial<T>(val value: T?)
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
data class DevToolsStep(val id: String, val runId: String, val stepNumber: Int, val type: String, val modelId: String, val provider: String, val input: JsonElement, val providerOptions: Map<String, JsonElement>)
Link copied to clipboard
data class DevToolsStepResult(val durationMs: Long, val output: JsonElement?, val usage: Usage?, val error: String?, val rawRequest: JsonElement? = null, val rawResponse: JsonElement? = null, val rawChunks: List<JsonElement> = emptyList())
Link copied to clipboard
data class DownloadedAsset(val base64: String, val mediaType: String?)

The base64 bytes + media type of a downloaded asset.

Link copied to clipboard
class DownloadError(val url: String, message: String, val statusCode: Int? = null, val statusText: String? = null, cause: Throwable? = null) : AiSdkException
Link copied to clipboard
typealias DownloadFunction = suspend (url: String) -> DownloadedAsset

Downloads a remote asset for convertToLanguageModelPrompt.

Link copied to clipboard
@Serializable
data class ElicitationCapability(val applyDefaults: Boolean? = null)
Link copied to clipboard
@Serializable
data class ElicitationRequest(val params: ElicitationRequestParams, val method: String = "elicitation/create")
Link copied to clipboard
@Serializable
data class ElicitationRequestParams(val message: String, val requestedSchema: JsonElement, val meta: JsonObject? = null)
Link copied to clipboard
Link copied to clipboard
@Serializable
data class ElicitResult(val action: String, val content: JsonObject? = null, val meta: JsonObject? = null)
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
interface EmbeddingModel
Link copied to clipboard
data class EmbeddingModelCallParams(val values: List<String>, val maxEmbeddingsPerCall: Int? = null, val truncate: Boolean? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever, val headers: Map<String, String> = emptyMap())
Link copied to clipboard
Link copied to clipboard
data class EmbeddingModelResult(val embeddings: List<List<Float>>, val usage: EmbeddingUsage = EmbeddingUsage(), val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
data class EmbeddingUsage(val tokens: Int = 0, val raw: JsonElement? = null)
Link copied to clipboard
data class EmbedManyResult<TValue>(val values: List<TValue>, val embeddings: List<List<Float>>, val usage: EmbeddingUsage, val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val responses: List<LanguageModelResponseMetadata> = emptyList(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
data class EmbedResult<TValue>(val value: TValue, val embedding: List<Float>, val usage: EmbeddingUsage, val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
class EmptyResponseBodyError(message: String = "Empty response body") : AiSdkException
Link copied to clipboard
sealed interface ExecuteToolResult<out TOutput>
Link copied to clipboard
Link copied to clipboard
class Experimental_StdioMCPTransport(val config: StdioConfig, engineContext: CoroutineContext = Dispatchers.Default) : MCPTransport
Link copied to clipboard
@RequiresOptIn(level = RequiresOptIn.Level.ERROR, message = "This is an experimental AI SDK API (framework-adapter / migration surface). It may change or be removed without notice. Opt in with @OptIn(ExperimentalAiSdkApi::class).")
annotation class ExperimentalAiSdkApi

Marks a declaration as experimental: a surface whose shape may change or be removed in any release without going through the normal deprecation cycle.

Link copied to clipboard
sealed interface FileData
Link copied to clipboard
@Serializable
enum FinishReason : Enum<FinishReason>

Why a generation step ended.

Link copied to clipboard
class GatewayAuthenticationError(message: String = "Authentication failed", statusCode: Int = 401, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
Link copied to clipboard
data class GatewayAuthToken(val token: String, val authMethod: GatewayAuthMethod)
Link copied to clipboard
data class GatewayCreditsResponse(val balance: String, val totalUsed: String)
Link copied to clipboard
Link copied to clipboard
open class GatewayError(message: String, val statusCode: Int = 500, val type: String = "gateway_error", val generationId: String? = null, cause: Throwable? = null, val isRetryable: Boolean = statusCode == 408 || statusCode == 409 || statusCode == 429 || statusCode >= 500) : AiSdkException
Link copied to clipboard
data class GatewayGenerationInfo(val id: String, val totalCost: Double, val upstreamInferenceCost: Double, val usage: Double, val createdAt: String, val model: String, val isByok: Boolean, val providerName: String, val streamed: Boolean, val finishReason: String, val latency: Int, val generationTime: Int, val promptTokens: Int, val completionTokens: Int, val reasoningTokens: Int, val cachedTokens: Int, val cacheCreationTokens: Int, val billableWebSearchCalls: Int)
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
class GatewayInternalServerError(message: String = "Internal server error", statusCode: Int = 500, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
class GatewayInvalidRequestError(message: String = "Invalid request", statusCode: Int = 400, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
data class GatewayLanguageModelEntry(val id: String, val name: String, val description: String? = null, val pricing: GatewayPricing? = null, val specification: GatewayLanguageModelSpecification, val modelType: GatewayModelType? = null)
Link copied to clipboard
data class GatewayLanguageModelSpecification(val specificationVersion: String = "v3", val provider: String, val modelId: String)
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
class GatewayModelNotFoundError(message: String = "Model not found", statusCode: Int = 404, val modelId: String? = null, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
Link copied to clipboard
data class GatewayPricing(val input: String, val output: String, val cachedInputTokens: String? = null, val cacheCreationInputTokens: String? = null)
Link copied to clipboard
Link copied to clipboard
data class GatewayProviderSettings(val baseUrl: String = AI_GATEWAY_DEFAULT_BASE_URL, val apiKey: String? = null, val headers: Map<String, String> = emptyMap(), val transport: GatewayTransport = GatewayTransportNotConfigured, val metadataCacheRefreshMillis: Long = 5 * 60 * 1000L, val nowMillis: () -> Long = { Clock.System.now().toEpochMilliseconds() }, val authTokenProvider: suspend () -> GatewayAuthToken?? = null, val environment: Map<String, String> = emptyMap())
Link copied to clipboard
class GatewayRateLimitError(message: String = "Rate limit exceeded", statusCode: Int = 429, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
data class GatewayRequestContext(val baseUrl: String, val headers: Map<String, String>)
Link copied to clipboard
Link copied to clipboard
class GatewayResponseError(message: String = "Invalid response from Gateway", statusCode: Int = 502, val response: JsonElement? = null, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
data class GatewaySpendReportParams(val startDate: String, val endDate: String, val groupBy: GatewaySpendReportGroupBy? = null, val datePart: GatewaySpendReportDatePart? = null, val userId: String? = null, val model: String? = null, val provider: String? = null, val credentialType: GatewayCredentialType? = null, val tags: List<String> = emptyList())
Link copied to clipboard
Link copied to clipboard
data class GatewaySpendReportRow(val day: String? = null, val hour: String? = null, val user: String? = null, val model: String? = null, val tag: String? = null, val provider: String? = null, val credentialType: GatewayCredentialType? = null, val totalCost: Double, val marketCost: Double? = null, val inputTokens: Int? = null, val outputTokens: Int? = null, val cachedInputTokens: Int? = null, val cacheCreationInputTokens: Int? = null, val reasoningTokens: Int? = null, val requestCount: Int? = null)
Link copied to clipboard
class GatewayTimeoutError(message: String = "Gateway request timed out", statusCode: Int = 408, generationId: String? = null, cause: Throwable? = null) : GatewayError
Link copied to clipboard
data class GatewayTools(val parallelSearch: Tool<JsonElement, JsonElement, Any?> = providerExecutedTool( name = "parallelSearch", description = "Search the web using Parallel AI's Search API for LLM-optimized excerpts.", inputSerializer = JsonElement.serializer(), outputSerializer = JsonElement.serializer(), ), val perplexitySearch: Tool<JsonElement, JsonElement, Any?> = providerExecutedTool( name = "perplexitySearch", description = "Search the web using Perplexity's Search API for real-time information.", inputSerializer = JsonElement.serializer(), outputSerializer = JsonElement.serializer(), ))
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
data class GeneratedFile(val mediaType: String, val base64: String, val filename: String? = null, val providerMetadata: Map<String, JsonElement> = emptyMap(), val url: String? = null)
Link copied to clipboard
data class GenerateImageResult(val images: List<GeneratedFile>, val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val responses: List<LanguageModelResponseMetadata> = listOf(response), val usage: ImageModelUsage = ImageModelUsage())
Link copied to clipboard
data class GenerateObjectResult<TOutput>(val value: TOutput, val text: String, val reasoning: String? = null, val finishReason: FinishReason, val usage: Usage, val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
data class GenerateResult<TOutput>(val output: TOutput, val text: String, val steps: List<StepResult>, val finishReason: FinishReason, val usage: Usage, val totalUsage: Usage = usage, val pendingApprovals: List<PendingApproval> = emptyList(), val messages: List<ModelMessage> = emptyList())

Final output of Agent.generate. When pendingApprovals is non-empty, the loop paused on tool approval — call Agent.generate again with messages plus tool-approval-response messages to resume.

Link copied to clipboard
data class GenerateSpeechResult(val audio: GeneratedFile, val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val responses: List<LanguageModelResponseMetadata> = listOf(response))
Link copied to clipboard
data class GenerateTextResult<TOutput>(val output: TOutput, val text: String, val toolCalls: List<ContentPart.ToolCall>, val finishReason: FinishReason, val usage: Usage, val content: List<ContentPart> = buildList { if (text.isNotEmpty()) add(ContentPart.Text(text)) addAll(toolCalls) }, val toolResults: List<ContentPart.ToolResult> = content.filterIsInstance<ContentPart.ToolResult>(), val reasoning: List<ContentPart.Reasoning> = content.filterIsInstance<ContentPart.Reasoning>(), val reasoningText: String? = reasoning.takeIf { it.isNotEmpty() }?.joinToString("") { it.text }, val files: List<ContentPart.File> = content.filterIsInstance<ContentPart.File>(), val sources: List<ContentPart.Source> = content.filterIsInstance<ContentPart.Source>(), val totalUsage: Usage = usage, val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val steps: List<StepResult> = emptyList(), val rawFinishReason: String? = null)
Link copied to clipboard
data class GenerateVideoResult(val videos: List<GeneratedFile>, val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val responses: List<LanguageModelResponseMetadata> = listOf(response))
Link copied to clipboard
@Serializable
data class GetPromptResult(val messages: List<MCPPromptMessage>, val description: String? = null, val meta: JsonObject? = null)
Link copied to clipboard
class HttpMCPTransport(client: HttpClient, url: String, headers: Map<String, String> = emptyMap(), authProvider: OAuthClientProvider? = null, engineContext: CoroutineContext = Dispatchers.Default) : MCPTransport
Link copied to clipboard
data class IdGenerator(val prefix: String? = null, val size: Int = 16, val alphabet: String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", val separator: String = "-", val random: Random = Random.Default)
Link copied to clipboard
data class ImageGenerationFile(val mediaType: String? = null, val base64: String? = null, val url: String? = null, val filename: String? = null)
Link copied to clipboard
data class ImageGenerationParams(val prompt: String, val n: Int = 1, val size: String? = null, val aspectRatio: String? = null, val seed: Int? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val headers: Map<String, String> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever, val files: List<ImageGenerationFile> = emptyList(), val mask: ImageGenerationFile? = null)
Link copied to clipboard
data class ImageMiddlewareCallContext(val params: ImageGenerationParams, val model: ImageModel, val doGenerate: suspend (ImageGenerationParams) -> ImageModelResult)
Link copied to clipboard
interface ImageModel
Link copied to clipboard
Link copied to clipboard
data class ImageModelResult(val images: List<GeneratedFile>, val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val usage: ImageModelUsage = ImageModelUsage())
Link copied to clipboard
data class ImageModelUsage(val inputTokens: Int? = null, val outputTokens: Int? = null, val totalTokens: Int? = null)

Token usage reported by an image model, when available. Mirrors v6's ImageModelUsage.

Link copied to clipboard
@Serializable
data class InitializeResult(val protocolVersion: String, val capabilities: MCPServerCapabilities = MCPServerCapabilities(), val serverInfo: Configuration, val instructions: String? = null, val meta: JsonObject? = null)
Link copied to clipboard
@RequiresOptIn(level = RequiresOptIn.Level.ERROR, message = "This is an internal AI SDK API and is not part of the public contract. It may change or be removed without notice. Opt in with @OptIn(InternalAiSdkApi::class).")
annotation class InternalAiSdkApi

Marks a declaration as internal to the AI SDK implementation: visible across module boundaries for technical reasons (KMP source sets, inlining), but not part of the supported public contract. It may change or be removed at any time.

Link copied to clipboard
class InvalidArgumentError(val argument: String, reason: String, cause: Throwable? = null) : AiSdkException
Link copied to clipboard
class InvalidDataContentError(val content: Any?, cause: Throwable? = null, message: String = "Invalid data content. Expected a base64 string, ByteArray, or platform byte buffer, " + "but got ${content?.let { it::class.simpleName } ?: "null"}.") : AiSdkException
Link copied to clipboard
class InvalidMessageRoleError(val role: String, message: String = "Invalid message role: '") : AiSdkException
Link copied to clipboard
class InvalidPromptError(val prompt: Any?, message: String, cause: Throwable? = null) : AiSdkException
Link copied to clipboard
class InvalidResponseDataError(val data: Any?, message: String = "Invalid response data: ") : AiSdkException
Link copied to clipboard
class InvalidStreamPartError(val chunk: Any?, message: String) : AiSdkException
Link copied to clipboard
Link copied to clipboard
class InvalidToolInputError(val toolInput: String, val toolName: String, cause: Throwable, message: String = "Invalid input for tool ") : AiSdkException
Link copied to clipboard
class JSONParseError(val text: String, cause: Throwable) : AiSdkException
Link copied to clipboard
@Serializable
data class JSONRPCError(val id: JsonElement, val error: JSONRPCErrorData, val jsonrpc: String = JSONRPC_VERSION) : JSONRPCMessage
Link copied to clipboard
@Serializable
data class JSONRPCErrorData(val code: Int, val message: String, val data: JsonElement? = null)
Link copied to clipboard
@Serializable
sealed interface JSONRPCMessage
Link copied to clipboard
@Serializable
data class JSONRPCNotification(val method: String, val params: JsonObject? = null, val jsonrpc: String = JSONRPC_VERSION) : JSONRPCMessage
Link copied to clipboard
@Serializable
data class JSONRPCRequest(val id: JsonElement, val method: String, val params: JsonObject? = null, val jsonrpc: String = JSONRPC_VERSION) : JSONRPCMessage
Link copied to clipboard
@Serializable
data class JSONRPCResponse(val id: JsonElement, val result: JsonElement = JsonObject(emptyMap()), val jsonrpc: String = JSONRPC_VERSION) : JSONRPCMessage
Link copied to clipboard
class KtorGatewayTransport(client: HttpClient, json: Json = aiSdkJson) : GatewayTransport
Link copied to clipboard
@Serializable
data class LangChainBaseMessage(val role: LangChainMessageRole, val content: JsonElement = JsonPrimitive(""), val id: String? = null, val toolCallId: String? = null, val toolCalls: List<LangChainToolCall> = emptyList(), val additionalKwargs: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
Link copied to clipboard
sealed interface LangChainStreamItem
Link copied to clipboard
@Serializable
data class LangChainToolCall(val id: String, val name: String, val input: JsonElement = JsonObject(emptyMap()))
Link copied to clipboard
class LangSmithDeploymentTransport(options: LangSmithDeploymentTransportOptions, graphStream: LangSmithGraphStream = { _, _ -> throw UnsupportedOperationException( "LangSmithDeploymentTransport requires a graphStream implementation in Kotlin Multiplatform.", ) }) : ChatTransport
Link copied to clipboard
data class LangSmithDeploymentTransportOptions(val url: String, val apiKey: String? = null, val graphId: String = "agent", val headers: Map<String, String> = emptyMap())
Link copied to clipboard
Link copied to clipboard
interface LanguageModel

Provider-neutral model surface. Per invariant I-4 / I-9, application code never depends on a specific provider — it depends on this interface, and provider-specific differences live in middleware (see LanguageModelMiddleware).

Link copied to clipboard
data class LanguageModelCallParams(val messages: List<ModelMessage>, val tools: List<LanguageModelTool> = emptyList(), val toolChoice: ToolChoice = ToolChoice.Auto, val temperature: Float? = null, val topP: Float? = null, val topK: Int? = null, val maxOutputTokens: Int? = null, val stopSequences: List<String> = emptyList(), val seed: Int? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever, val presencePenalty: Float? = null, val frequencyPenalty: Float? = null, val responseFormat: ResponseFormat = ResponseFormat.Text, val headers: Map<String, String> = emptyMap())

Single parameter envelope for both generate and stream so middleware can wrap both the same way and wrapLanguageModel only needs one pass-through shape.

Link copied to clipboard

Provider middleware. Per invariants I-9 and R-11, provider differences (Anthropic-specific options, OpenAI-specific options, on-device-only sampling knobs) live in middleware — NEVER in agent or orchestration code. If you find yourself branching on model.modelId.startsWith("...") inside an agent, that's a missing middleware.

Link copied to clipboard
data class LanguageModelRequestMetadata(val body: JsonElement? = null)

Request metadata recorded by HTTP-backed or gateway providers.

Link copied to clipboard
data class LanguageModelResponseMetadata(val id: String? = null, val timestampMillis: Long? = null, val modelId: String? = null, val headers: Map<String, String> = emptyMap(), val body: JsonElement? = null, val messages: List<ModelMessage> = emptyList())

Response metadata recorded by HTTP-backed or gateway providers.

Link copied to clipboard
data class LanguageModelResult(val text: String, val toolCalls: List<ContentPart.ToolCall> = emptyList(), val finishReason: FinishReason, val usage: Usage, val providerMetadata: Map<String, JsonElement> = emptyMap(), val content: List<ContentPart> = buildList { if (text.isNotEmpty()) add(ContentPart.Text(text)) addAll(toolCalls) }, val rawFinishReason: String? = null, val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata())

One-shot generate result.

Link copied to clipboard
data class LanguageModelStreamResult(val stream: Flow<StreamEvent>, val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata())

Provider stream plus request/response metadata known before collection.

Link copied to clipboard
data class LanguageModelTool(val name: String, val description: String, val parametersSchemaJson: String, val providerExecuted: Boolean = false, val metadata: Map<String, JsonElement> = emptyMap(), val strict: Boolean = true, val providerOptions: Map<String, JsonElement> = emptyMap())

Tool advertisement at the model surface — the JSON-schema shape the provider needs. Distinct from the application-side Tool which carries a Kotlin executor; this is the wire shape that crosses into a provider.

Link copied to clipboard
class LazySchema<T>(createSchema: () -> Schema<T>)
Link copied to clipboard
@Serializable
data class ListPromptsResult(val prompts: List<MCPPrompt>, val nextCursor: String? = null, val meta: JsonObject? = null)
Link copied to clipboard
@Serializable
data class ListResourcesResult(val resources: List<MCPResource>, val nextCursor: String? = null, val meta: JsonObject? = null)
Link copied to clipboard
@Serializable
data class ListResourceTemplatesResult(val resourceTemplates: List<MCPResourceTemplate>, val nextCursor: String? = null, val meta: JsonObject? = null)
Link copied to clipboard
@Serializable
data class ListToolsResult(val tools: List<MCPToolDefinition>, val nextCursor: String? = null, val meta: JsonObject? = null)
Link copied to clipboard
data class LlamaIndexEngineResponse(val delta: String)
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
interface Logger

Port-side log sink for non-fatal warnings and informational events. Mirrors v6's logger/log-warnings.ts (per historical parity gap #31) — the agent loop, middleware, and tool dispatch surface warnings here so consumers can route them to Logcat / Crashlytics / their own telemetry without the port hard-coding a logging dependency.

Link copied to clipboard
data class LoopState(val stepNumber: Int, val totalSteps: Int, val lastFinishReason: FinishReason, val toolCallsThisStep: List<ContentPart.ToolCall>, val toolCallsAllSteps: List<ContentPart.ToolCall>, val steps: List<StepResult> = emptyList())
Link copied to clipboard
@Serializable
data class MCPBaseParams(val meta: JsonObject? = null)
Link copied to clipboard
interface MCPClient
Link copied to clipboard
@Serializable
data class MCPClientCapabilities(val elicitation: ElicitationCapability? = null, val experimental: JsonObject? = null)
Link copied to clipboard
data class MCPClientConfig(val transport: MCPTransport, val onUncaughtError: (Throwable) -> Unit? = null, val clientName: String? = null, val name: String? = null, val version: String = DEFAULT_MCP_CLIENT_VERSION, val capabilities: MCPClientCapabilities = MCPClientCapabilities())
Link copied to clipboard
class MCPClientError(message: String, val code: Int? = null, val data: JsonElement? = null, cause: Throwable? = null) : AiSdkException
Link copied to clipboard
@Serializable
data class MCPPrompt(val name: String, val title: String? = null, val description: String? = null, val arguments: List<MCPPromptArgument>? = null)
Link copied to clipboard
@Serializable
data class MCPPromptArgument(val name: String, val description: String? = null, val required: Boolean? = null)
Link copied to clipboard
@Serializable
data class MCPPromptMessage(val role: String, val content: JsonObject)
Link copied to clipboard
data class MCPRequestOptions(val signal: AbortSignal? = null, val timeoutMillis: Long? = null, val maxTotalTimeoutMillis: Long? = null)
Link copied to clipboard
@Serializable
data class MCPResource(val uri: String, val name: String, val title: String? = null, val description: String? = null, val mimeType: String? = null, val size: Long? = null)
Link copied to clipboard
@Serializable
data class MCPResourceTemplate(val uriTemplate: String, val name: String, val title: String? = null, val description: String? = null, val mimeType: String? = null)
Link copied to clipboard
@Serializable
data class MCPServerCapabilities(val experimental: JsonObject? = null, val logging: JsonObject? = null, val prompts: JsonObject? = null, val resources: JsonObject? = null, val tools: JsonObject? = null, val elicitation: ElicitationCapability? = null)
Link copied to clipboard
@Serializable
data class MCPToolDefinition(val name: String, val title: String? = null, val description: String? = null, val inputSchema: JsonObject = JsonObject(mapOf("type" to JsonPrimitive("object"))), val outputSchema: JsonObject? = null, val annotations: JsonObject? = null, val meta: JsonObject? = null)
Link copied to clipboard
@Serializable
data class MCPToolSchema(val inputSchema: JsonElement, val outputSchema: JsonElement? = null)
Link copied to clipboard
Link copied to clipboard
interface MCPTransport

Transport interface for MCP communication. Implementations may wrap stdio, Streamable HTTP, SSE, WebSockets, or a test fixture.

Link copied to clipboard
data class MCPTransportConfig(val type: MCPTransportKind, val url: String, val headers: Map<String, String> = emptyMap(), val authProvider: OAuthClientProvider? = null, val engineContext: CoroutineContext = Dispatchers.Default)
Link copied to clipboard
Link copied to clipboard
class MessageConversionError(val originalMessage: Any?, message: String) : AiSdkException
Link copied to clipboard
@Serializable
enum MessageRole : Enum<MessageRole>
Link copied to clipboard
data class MiddlewareCallContext(val params: LanguageModelCallParams, val model: LanguageModel, val doGenerate: suspend (LanguageModelCallParams) -> LanguageModelResult, val doStream: (LanguageModelCallParams) -> Flow<StreamEvent>)

What a middleware receives. Contains:

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
value class ModelId(val value: String)
Link copied to clipboard
@Serializable
data class ModelMessage(val role: MessageRole, val content: List<ContentPart>)

v6 wire-shape message — the type passed to LanguageModel generations. Renamed from CoreMessage (v5) per the AI SDK v6 migration.

Link copied to clipboard
data class ModelRef(val modelId: ModelId, val providerId: ProviderId? = null)
Link copied to clipboard
class MutableTelemetrySpan(val name: String, mutableAttributes: MutableMap<String, JsonElement> = linkedMapOf()) : TelemetryActiveSpan
Link copied to clipboard
class NoContentGeneratedError(message: String = "No content generated.") : AiSdkException
Link copied to clipboard
class NoImageGeneratedError(message: String = "No image generated", val responses: List<LanguageModelResponseMetadata> = emptyList(), cause: Throwable? = null) : AiSdkException
Link copied to clipboard
class NoObjectGeneratedError(message: String = "No object generated", val text: String? = null, val response: LanguageModelResponseMetadata? = null, val usage: Usage? = null, val finishReason: FinishReason? = null, cause: Throwable? = null) : AiSdkException

Thrown when no object could be generated (the model failed, or its output could not be parsed/validated). Carries the diagnostic context upstream's NoObjectGeneratedError exposes so callers can inspect the raw text, the response metadata, the token usage, and the finish reason of the failed call.

Link copied to clipboard
data object NoopLogger : Logger

Drop-everything logger. Default when no DI-injected impl is wired.

Link copied to clipboard
Link copied to clipboard

No-op ToolStreamWriter — the default on a ToolExecutionContext constructed outside the loop (test fixtures, the approval-resume path before the loop wires a real writer). Drops every write.

Link copied to clipboard
class NoOutputGeneratedError(message: String = "No output generated") : AiSdkException
Link copied to clipboard
class NoSpeechGeneratedError(message: String = "No speech generated", val responses: List<LanguageModelResponseMetadata> = emptyList(), cause: Throwable? = null) : AiSdkException
Link copied to clipboard
class NoSuchModelError(providerId: String?, modelType: String, modelId: String, message: String = buildString { append("No ") append(modelType) append(" model registered for `") providerId?.let { append(it).append(":") } append(modelId) append("`") }) : AiSdkException
Link copied to clipboard
class NoSuchProviderError(val providerId: String, val availableProviders: List<String> = emptyList()) : AiSdkException
Link copied to clipboard
class NoSuchToolError(val toolName: String, val availableTools: List<String>? = null, message: String = "Model tried to call unavailable tool '$toolName'. " + if (availableTools == null) { "No tools are available." } else { "Available tools: ${availableTools.joinToString(", ")}." }) : AiSdkException
Link copied to clipboard
class NoTranscriptGeneratedError(message: String = "No transcript generated", val responses: List<LanguageModelResponseMetadata> = emptyList(), cause: Throwable? = null) : AiSdkException
Link copied to clipboard
class NoVideoGeneratedError(message: String = "No video generated", val responses: List<LanguageModelResponseMetadata> = emptyList(), cause: Throwable? = null) : AiSdkException
Link copied to clipboard
@Serializable
data class OAuthClientInformation(val clientId: String, val clientSecret: String? = null, val clientIdIssuedAt: Long? = null, val clientSecretExpiresAt: Long? = null)
Link copied to clipboard
@Serializable
data class OAuthClientMetadata(val redirectUris: List<String>, val tokenEndpointAuthMethod: String? = null, val grantTypes: List<String>? = null, val responseTypes: List<String>? = null, val clientName: String? = null, val clientUri: String? = null, val logoUri: String? = null, val scope: String? = null, val contacts: List<String>? = null, val tosUri: String? = null, val policyUri: String? = null, val jwksUri: String? = null, val jwks: JsonElement? = null, val softwareId: String? = null, val softwareVersion: String? = null, val softwareStatement: String? = null)
Link copied to clipboard
Link copied to clipboard
@Serializable
data class OAuthProtectedResourceMetadata(val resource: String, val authorizationServers: List<String>? = null, val jwksUri: String? = null, val scopesSupported: List<String>? = null, val bearerMethodsSupported: List<String>? = null, val resourceName: String? = null)
Link copied to clipboard
@Serializable
data class OAuthTokens(val accessToken: String, val tokenType: String, val idToken: String? = null, val expiresIn: Long? = null, val scope: String? = null, val refreshToken: String? = null)
Link copied to clipboard
data class OnAbortEvent(val steps: List<StepResult>)

Fired when generation is aborted via AbortSignal before it finishes. Carries the steps completed up to the abort. Mirrors upstream's onAbort({ steps }).

Link copied to clipboard
data class OnChunkEvent(val event: StreamEvent, val stepNumber: Int)

Each individual stream chunk, alongside the step it belongs to.

Link copied to clipboard
data class OnErrorEvent(val error: Throwable, val stepNumber: Int, val source: OnErrorEvent.ErrorSource)
Link copied to clipboard
data class OnFinishEvent(val finalOutput: Any?, val totalSteps: Int, val usage: Usage, val pendingApprovals: List<PendingApproval> = emptyList(), val messages: List<ModelMessage> = emptyList(), val experimental_context: Any? = null)
Link copied to clipboard
data class OnStartEvent(val prompt: String?, val priorMessages: List<ModelMessage>, val options: Any?)

Lifecycle hook event types (best practice #10). Hooks are observation points — they do NOT modify behavior. If a hook needs to influence the loop, the right place is PrepareStepScope / PrepareCallScope.

Link copied to clipboard
data class OnStepFinishEvent(val stepNumber: Int, val step: StepResult)
Link copied to clipboard
data class OnStepStartEvent(val stepNumber: Int, val messages: List<ModelMessage>, val request: LanguageModelCallParams? = null, val priorSteps: List<StepResult> = emptyList())

Fired before each loop step's model call. Per historical parity gap #35, the payload was extended from (stepNumber, messages) to carry the full prepared request (post prepareCall + prepareStep overrides) plus accumulated priorSteps so observers can:

Link copied to clipboard
data class OnToolCallFinishEvent(val toolCallId: String, val toolName: String, val outputJson: JsonElement?, val errorMessage: String?, val stepNumber: Int)

Fired immediately after a tool's executor returns or throws. Exactly one of outputJson or errorMessage is non-null.

Link copied to clipboard
data class OnToolCallStartEvent(val toolCallId: String, val toolName: String, val input: JsonElement, val stepNumber: Int, val messages: List<ModelMessage>)

Fired immediately before a tool's executor runs. Carries the parsed tool call envelope and the messages-list snapshot so observers can record context (e.g. for tracing).

Link copied to clipboard
sealed class Output<T>

Structured output for generateText / streamText / Agent.

Link copied to clipboard
sealed interface ParseResult<out T>
Link copied to clipboard
data class PartialJsonResult(val value: JsonElement?, val state: PartialJsonState)

Result of parsePartialJson: value is non-null only on the two success states.

Link copied to clipboard

Outcome of parsePartialJson, mirroring v6's four state strings.

Link copied to clipboard
@Serializable
data class PendingApproval(val toolCallId: String, val toolName: String, val input: JsonElement, val approvalId: String? = null, val signature: String? = null)

A pending tool-call approval surfaced from Agent.generate / Agent.stream. Per v6 RPC semantics, generation completes when one or more tools require approval — the host inspects GenerateResult.pendingApprovals, presents UI, and resumes by calling Agent.generate again with messages = result.messages + toolApprovalResponseMessage(...).

Link copied to clipboard
class PrepareCallScope<TContext>(val options: TContext?, val instructions: String, val model: LanguageModel, val tools: ToolSet<TContext>)

Scope for prepareCall, run once before the loop starts. Useful for RAG context injection, per-user customization, database lookups that shouldn't repeat per step.

Link copied to clipboard
class PrepareStepScope<TContext>(val stepNumber: Int, val model: LanguageModel, val steps: List<StepResult>, val messages: List<ModelMessage>, val context: TContext?)

Scope for prepareStep, run before every step in the loop. Used for: model routing per step (cheap model for step 1 + 2, expensive for step 3), tool gating per step (only the search tool is callable on step 1), dynamic system prompts, message compression.

Link copied to clipboard
interface Provider
Link copied to clipboard
value class ProviderId(val value: String)
Link copied to clipboard
data class ProviderMiddleware(val languageModelMiddlewares: List<LanguageModelMiddleware> = emptyList(), val embeddingModelMiddlewares: List<EmbeddingModelMiddleware> = emptyList(), val imageModelMiddlewares: List<ImageModelMiddleware> = emptyList())
Link copied to clipboard
Link copied to clipboard
class ProviderRegistry(providers: Map<String, Provider>, defaultProviderId: String? = null, separator: String = ":", languageModelMiddleware: List<LanguageModelMiddleware> = emptyList()) : Provider
Link copied to clipboard
class ProviderToolFactory<TInput, TContext>(id: String, inputSerializer: KSerializer<TInput>, inputSchema: Schema<TInput>, defaultDescription: String = "Provider tool ")
Link copied to clipboard
data class ProviderToolFactoryOptions<TInput, TOutput, TContext>(val outputSerializer: KSerializer<TOutput>, val outputSchema: Schema<TOutput>? = null, val args: Map<String, JsonElement> = emptyMap(), val name: String? = null, val description: String? = null, val metadata: Map<String, JsonElement> = emptyMap(), val execute: suspend ToolExecutionContext<TContext>.(TInput) -> TOutput? = null, val needsApproval: suspend (input: TInput, options: ToolPredicateOptions<TContext>) -> Boolean? = null, val toModelOutput: (TOutput, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, val onInputStart: suspend (streamingId: String) -> Unit? = null, val onInputDelta: suspend (streamingId: String, delta: String) -> Unit? = null, val onInputAvailable: suspend (toolCallId: String, input: TInput) -> Unit? = null)
Link copied to clipboard
class ProviderToolFactoryWithOutputSchema<TInput, TOutput, TContext>(id: String, inputSerializer: KSerializer<TInput>, inputSchema: Schema<TInput>, outputSerializer: KSerializer<TOutput>, outputSchema: Schema<TOutput>, supportsDeferredResults: Boolean = false, defaultDescription: String = "Provider tool ")
Link copied to clipboard
Link copied to clipboard
data class PruneToolCallRule(val type: PruneToolCallRuleType, val tools: Set<String>? = null)
Link copied to clipboard
Link copied to clipboard
sealed class PruneToolCalls
Link copied to clipboard
@Serializable
data class ReadResourceResult(val contents: List<JsonObject>, val meta: JsonObject? = null)
Link copied to clipboard
data class RerankedItem<T>(val value: T, val score: Float, val index: Int)
Link copied to clipboard
interface RerankingModel
Link copied to clipboard
data class RerankingModelResult(val results: List<RerankedItem<String>>, val usage: Usage = Usage(), val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
data class RerankingParams(val query: String, val documents: List<String>, val topN: Int? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val headers: Map<String, String> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever)
Link copied to clipboard
data class RerankResult<T>(val results: List<RerankedItem<T>>, val originalDocuments: List<T> = emptyList(), val usage: Usage = Usage(), val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
@Serializable
sealed interface ResponseFormat

Wire-level constraint on what shape the model is allowed to emit. Mirrors v6's responseFormat (per call-settings.ts:103-128 → historical parity gap #20). Distinct from Output — Output is the post-decode wrapper that turns text into typed values; ResponseFormat is what the provider sees at call time.

Link copied to clipboard
class RetryError(message: String, val reason: RetryErrorReason, val errors: List<Throwable>) : AiSdkException
Link copied to clipboard
Link copied to clipboard
data class RetryPolicy(val maxRetries: Int = 2, val baseDelayMs: Long = 100, val maxDelayMs: Long)
Link copied to clipboard
data class Schema<T>(val jsonSchema: JsonElement, val validate: (JsonElement) -> T? = null)
Link copied to clipboard
data class SpeechGenerationParams(val text: String, val voice: String? = null, val instructions: String? = null, val speed: Float? = null, val responseFormat: String? = null, val language: String? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val headers: Map<String, String> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever)
Link copied to clipboard
interface SpeechModel
Link copied to clipboard
data class SpeechModelResult(val audio: GeneratedFile?, val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
class SseMCPTransport(client: HttpClient, url: String, headers: Map<String, String> = emptyMap(), authProvider: OAuthClientProvider? = null, engineContext: CoroutineContext = Dispatchers.Default) : MCPTransport
Link copied to clipboard
@Serializable
data class StdioConfig(val command: String, val args: List<String> = emptyList(), val env: Map<String, String> = emptyMap(), val cwd: String? = null)
Link copied to clipboard
data class StepResult(val stepNumber: Int, val text: String, val reasoning: String, val toolCalls: List<ContentPart.ToolCall>, val toolResults: List<ContentPart.ToolResult>, val toolApprovalRequests: List<ContentPart.ToolApprovalRequest>, val finishReason: FinishReason, val usage: Usage, val warnings: List<CallWarning> = emptyList(), val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val rawFinishReason: String? = null, val model: String? = null, val experimentalContext: Any? = null)

Snapshot of one completed loop step — surfaced to OnStepFinishEvent and accumulated in the loop state for PrepareStepScope.steps.

Link copied to clipboard
data class StepSettings<TContext>(val model: LanguageModel? = null, val activeTools: List<String>? = null, val toolChoice: ToolChoice? = null, val messages: List<ModelMessage>? = null, val system: String? = null, val providerOptions: Map<String, JsonElement>? = null, val temperature: Float? = null, val topP: Float? = null, val topK: Int? = null, val maxOutputTokens: Int? = null, val stopSequences: List<String>? = null, val seed: Int? = null, val presencePenalty: Float? = null, val frequencyPenalty: Float? = null, val responseFormat: ResponseFormat? = null, val experimental_context: TContext? = null)

Returned from prepareStep. Any non-null field overrides the agent default / prepareCall value for this step only.

Link copied to clipboard
fun interface StopCondition

First-class loop stop conditions (invariant I-7). The SDK manages the loop; consumers express completion as a StopCondition passed to the agent constructor or generateText.

Link copied to clipboard
data class StreamCallbacks(val onStart: suspend () -> Unit? = null, val onFinal: suspend (completion: String) -> Unit? = null, val onToken: suspend (token: String) -> Unit? = null, val onText: suspend (text: String) -> Unit? = null, val onFinish: suspend (finalState: JsonElement?) -> Unit? = null, val onError: suspend (error: Throwable) -> Unit? = null, val onAbort: suspend () -> Unit? = null)
Link copied to clipboard
@Serializable
sealed interface StreamEvent

Sealed event stream emitted by LanguageModel.stream and surfaced to application code via Agent.stream. Mirrors the v6 stream-part taxonomy (per packages/ai/src/generate-text/stream-text-result.ts in vercel/ai) adapted to Kotlin sealed classes for exhaustive when.

Link copied to clipboard
data class StreamObjectFinish<TOutput>(val value: TOutput, val usage: Usage, val finishReason: FinishReason, val warnings: List<CallWarning>, val response: LanguageModelResponseMetadata)

The final object plus terminal metadata of a StreamObjectResult.finish.

Link copied to clipboard

A typed streaming-object result — the v6 StreamObjectResult surface. Wraps the underlying StreamEvent flow so callers get the object as it builds and the final typed value, without hand-parsing the stream.

Link copied to clipboard
class StreamTextResult(sourceStream: Flow<StreamEvent>, val request: LanguageModelRequestMetadata = LanguageModelRequestMetadata(), initialResponse: LanguageModelResponseMetadata = LanguageModelResponseMetadata())
Link copied to clipboard
Link copied to clipboard
data class StructuredObjectFinish<RESULT>(val value: RESULT?, val error: Throwable?, val rawValue: JsonElement?)
Link copied to clipboard
data class StructuredObjectOptions<RESULT, INPUT>(val api: String, val schema: Schema<RESULT>, val id: String = generateId("object"), val initialValue: RESULT? = null, val headers: Map<String, String> = emptyMap(), val transport: StructuredObjectTransport<INPUT> = DirectStructuredObjectTransport { emptyFlow() }, val onFinish: suspend (StructuredObjectFinish<RESULT>) -> Unit = {}, val onError: suspend (Throwable) -> Unit = {})
Link copied to clipboard
data class StructuredObjectRequest<INPUT>(val api: String, val id: String, val input: INPUT, val headers: Map<String, String> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever)
Link copied to clipboard
Link copied to clipboard
interface Telemetry

The v7 telemetry integration seam (upstream's Telemetry, the revamped TelemetryIntegration): implement it ONCE and the loop feeds it every lifecycle event of every invocation — agent start/finish, step start/finish, model-call start/finish, tool-call start/finish (including tool executions resumed after an approval pause), errors, and aborts. Upstream: "Instead of wiring up individual callbacks on every call, you implement a Telemetry once and register it globally or pass it via telemetry.integrations."

Link copied to clipboard
Link copied to clipboard
data class TelemetryCall(val callId: String, val agentId: String, val agentVersion: String? = null, val modelId: String? = null, val functionId: String? = null)

Correlation envelope for one agent invocation (one generate/stream call). Every Telemetry event of that invocation carries the same callId, so an integration can reconstruct per-call traces even when a single agent instance serves concurrent calls. agentId/agentVersion mirror Agent.id/Agent.version (parity gap #33: "useful for telemetry"); functionId comes from TelemetrySettings.functionId.

Link copied to clipboard
data class TelemetryModelCallEvent(val stepNumber: Int, val modelId: String?, val params: LanguageModelCallParams)

Fired before one step's model call — carries the EXACT prepared params sent to the provider.

Link copied to clipboard
data class TelemetryModelCallResultEvent(val stepNumber: Int, val modelId: String?, val finishReason: FinishReason, val usage: Usage, val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val rawFinishReason: String? = null)

Fired after one step's model call streamed to completion.

Link copied to clipboard
class TelemetryRegistry(seed: List<Telemetry> = emptyList())

Ordered registry of Telemetry integrations, keyed by Telemetry.name (re-register replaces, keeping the original position).

Link copied to clipboard
data class TelemetrySettings(val isEnabled: Boolean? = null, val functionId: String? = null, val metadata: Map<String, JsonElement> = emptyMap(), val recordInputs: Boolean = true, val recordOutputs: Boolean = true, val integrations: List<Telemetry> = emptyList(), val tracer: TelemetryTracer? = null)

Telemetry settings for an agent or call (upstream v7 telemetry, the stabilized experimental_telemetry). With the v7 revamp, telemetry is opt-out: once an integration is registered via registerTelemetry, every agent invocation emits events to it automatically.

Link copied to clipboard
data class TelemetrySpanEvent(val name: String, val attributes: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
sealed interface TelemetrySpanStatus
Link copied to clipboard
interface TelemetryTracer
Link copied to clipboard
data class TextGenerationRequest(val prompt: String? = null, val messages: List<ModelMessage> = emptyList(), val system: String? = null, val settings: CallSettings = CallSettings())
Link copied to clipboard
class Tool<TInput, TOutput, TContext>(val name: String, val description: String, val inputSerializer: KSerializer<TInput>, val outputSerializer: KSerializer<TOutput>, val executor: ToolExecutionContext<TContext>.(TInput) -> Flow<TOutput>, val needsApproval: suspend (input: TInput, options: ToolPredicateOptions<TContext>) -> Boolean? = null, val toModelOutput: (TOutput, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, val strict: Boolean = true, val inputExamples: List<String> = emptyList(), val onInputStart: suspend (streamingId: String) -> Unit? = null, val onInputDelta: suspend (streamingId: String, delta: String) -> Unit? = null, val onInputAvailable: suspend (toolCallId: String, input: TInput) -> Unit? = null, val metadata: Map<String, JsonElement> = emptyMap(), val providerExecuted: Boolean = false, val providerOptions: Map<String, JsonElement> = emptyMap())

A tool the LLM can call — application code constructs these via the top-level tool (single-value) or streamingTool (Flow) factories.

Link copied to clipboard
class ToolCallNotFoundForApprovalError(val toolCallId: String, val approvalId: String) : AiSdkException
Link copied to clipboard
class ToolCallRepairError(val originalError: Throwable, cause: Throwable, message: String = "Error repairing tool call: ") : AiSdkException
Link copied to clipboard
typealias ToolCallRepairFunction<TContext> = suspend (failedCall: ContentPart.ToolCall, error: Throwable, messages: List<ModelMessage>, tools: ToolSet<TContext>) -> ContentPart.ToolCall?

Callback invoked when a tool call's JSON arguments fail to decode (the model emitted JSON that doesn't match the tool's input schema, or referenced an unknown tool). Return a corrected ContentPart.ToolCall to retry execution, or null to give up (the loop emits StreamEvent.ToolError for this call).

Link copied to clipboard
@Serializable
sealed interface ToolChoice

Whether the LLM should call a tool, no tool, a specific tool, etc.

Link copied to clipboard
class ToolExecutionContext<TContext>(val context: TContext?, val abortSignal: AbortSignal, val stepNumber: Int, val messages: List<ModelMessage>, val toolCallId: String, val writer: ToolStreamWriter = NoopToolStreamWriter)

What Tool.executor sees as this. Holds the typed application context (whatever the agent's callOptionsSchema says) plus the abort signal (invariant I-10: subagent tool handlers MUST forward this), the current step number, and the running message list.

Link copied to clipboard
abstract class ToolLoopAgent<TContext, TOutput>(val model: LanguageModel, val instructions: String, val tools: ToolSet<TContext>, val activeTools: List<String>? = null, val output: Output<TOutput>? = null, val stopWhen: StopCondition = stepCountIs(20), val prepareCall: suspend PrepareCallScope<TContext>.() -> AgentSettings<TContext>? = null, val prepareStep: suspend PrepareStepScope<TContext>.() -> StepSettings<TContext>? = null, val callOptionsSchema: KSerializer<TContext>? = null, val temperature: Float? = null, val topP: Float? = null, val topK: Int? = null, val maxOutputTokens: Int? = null, val stopSequences: List<String>? = null, val seed: Int? = null, val presencePenalty: Float? = null, val frequencyPenalty: Float? = null, val responseFormat: ResponseFormat = ResponseFormat.Text, val maxParallelToolCalls: Int = Int.MAX_VALUE, val onStart: suspend OnStartEvent.() -> Unit? = null, val onStepStart: suspend OnStepStartEvent.() -> Unit? = null, val onStepFinish: suspend OnStepFinishEvent.() -> Unit? = null, val onFinish: suspend OnFinishEvent.() -> Unit? = null, val onError: suspend OnErrorEvent.() -> Unit? = null, val onChunk: suspend OnChunkEvent.() -> Unit? = null, val onAbort: suspend OnAbortEvent.() -> Unit? = null, val experimental_onToolCallStart: suspend OnToolCallStartEvent.() -> Unit? = null, val experimental_onToolCallFinish: suspend OnToolCallFinishEvent.() -> Unit? = null, val experimental_repairToolCall: ToolCallRepairFunction<TContext>? = null, val experimental_toolApprovalSecret: ByteArray? = null, val telemetry: TelemetrySettings? = null, val logger: Logger = NoopLogger, engineContext: CoroutineContext = Dispatchers.Default) : Agent<TContext, TOutput>

Abstract base Agent implementation — the canonical v6 ToolLoopAgent. Extend it; do not instantiate it. A concrete agent subclasses this (e.g. class MyAgent(...) : ToolLoopAgent<C, O>(...)) so the agent's identity, tools, lifecycle overrides, and DI live in one named type — never a bare ToolLoopAgent(...) held as a field.

Link copied to clipboard
sealed interface ToolLoopAgentAction<out TContext>

Actions the host dispatches to drive the agent. Mirrors the Action sealed type a Compose ViewModel exposes — the agent is the "model" of an MVI loop.

Link copied to clipboard
data class ToolLoopAgentState(val messages: List<ModelMessage> = emptyList(), val streamingAssistantText: String = "", val currentToolCalls: List<ContentPart.ToolCall> = emptyList(), val pendingApprovals: List<PendingApproval> = emptyList(), val isStreaming: Boolean = false, val isModelLoading: Boolean = false, val error: String? = null, val totalSteps: Int = 0, val lastFinishReason: FinishReason? = null)

Engine-shape state for ToolLoopAgent.

Link copied to clipboard
data class ToolNameMapping(customToolNameToProviderToolName: Map<String, String>, providerToolNameToCustomToolName: Map<String, String>)
Link copied to clipboard
data class ToolPredicateOptions<TContext>(val toolCallId: String, val messages: List<ModelMessage>, val experimental_context: TContext? = null)

Options bag passed to predicate callbacks (Tool.needsApproval, Tool.toModelOutput). Mirrors v6's {toolCallId, messages, experimental_context} argument shape (per historical parity gap #17). Lets a predicate decide based on the conversation history or the current call's identity, not just the input.

Link copied to clipboard
@Serializable
sealed class ToolResultOutput

Structured return type for Tool.toModelOutput. Replaces the flat String return per historical parity gap #14. Lets a tool supply EITHER a short plain-text summary OR a structured JSON payload OR a typed error to the model — the agent's loop bridges each into the wire-format ContentPart.ToolResult.modelVisible appropriately:

Link copied to clipboard
class ToolSet<TContext>(val byName: Map<String, Tool<*, *, TContext>>)

Erased map of tools indexed by name — what the agent loop actually carries. Application code constructs via toolSetOf.

Link copied to clipboard
Link copied to clipboard

Lets a tool's executor write custom events into the agent's active output stream — the port's equivalent of v6's UIMessageStreamWriter (per historical parity gap #21). Distinct from the streamingTool mechanism (which surfaces progress as ToolResult(preliminary = true)): the writer pushes ARBITRARY StreamEvents — e.g. a transient status line (StreamEvent.TextDelta) or a custom data payload (StreamEvent.Raw via writeData) — that don't have to be tool-result-shaped. Writes interleave with the tool's own emissions in stream order. streamToUiMessages ignores Raw by default, so a consumer that wants custom data intercepts the Flow<StreamEvent> before UI conversion.

Link copied to clipboard
class TooManyEmbeddingValuesForCallError(val provider: String, val modelId: String, val maxEmbeddingsPerCall: Int, val values: List<Any?>) : AiSdkException
Link copied to clipboard
data class TranscribeResult(val text: String, val segments: List<TranscriptSegment> = emptyList(), val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val responses: List<LanguageModelResponseMetadata> = listOf(response), val language: String? = null, val durationInSeconds: Float? = null)
Link copied to clipboard
Link copied to clipboard
data class TranscriptionModelResult(val text: String?, val segments: List<TranscriptSegment> = emptyList(), val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap(), val language: String? = null, val durationInSeconds: Float? = null)
Link copied to clipboard
data class TranscriptionParams(val audio: AudioSource, val language: String? = null, val prompt: String? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val headers: Map<String, String> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever)
Link copied to clipboard
data class TranscriptSegment(val text: String, val startSeconds: Float? = null, val endSeconds: Float? = null)
Link copied to clipboard
data class TypeValidationContext(val field: String? = null, val entityName: String? = null, val entityId: String? = null)
Link copied to clipboard
class TypeValidationError(val value: Any?, cause: Throwable, val context: TypeValidationContext? = null) : AiSdkException
Link copied to clipboard
class UiMessageStreamError(message: String, cause: Throwable? = null) : AiSdkException
Link copied to clipboard
class UnauthorizedError(message: String = "Unauthorized") : AiSdkException
Link copied to clipboard
class UnsupportedFunctionalityError(val functionality: String, message: String = "'") : AiSdkException
Link copied to clipboard
Link copied to clipboard
@Serializable
data class Usage(val inputTokens: Usage.InputTokenBreakdown = InputTokenBreakdown(), val outputTokens: Usage.OutputTokenBreakdown = OutputTokenBreakdown(), val raw: JsonElement? = null)

Token-usage tracking, surfaced on completed steps and final results. Per historical parity gap #19, the shape mirrors v6's rich tree — input tokens split into noCache / cacheRead / cacheWrite and output tokens split into text / reasoning plus a raw slot for provider-specific payloads.

Link copied to clipboard
data class UseCompletionOptions(val api: String = "/api/completion", val id: String = generateId("completion"), val initialCompletion: String = "", val initialInput: String = "", val headers: Map<String, String> = emptyMap(), val body: Map<String, JsonElement> = emptyMap(), val streamProtocol: CompletionStreamProtocol = CompletionStreamProtocol.Data, val transport: CompletionTransport = DirectCompletionTransport { emptyFlow() }, val onFinish: suspend (prompt: String, completion: String) -> Unit = { _, _ -> }, val onError: suspend (Throwable) -> Unit = {})
Link copied to clipboard
sealed interface ValidationResult<out T>
Link copied to clipboard
data class VideoGenerationParams(val prompt: String, val n: Int = 1, val image: GeneratedFile? = null, val durationSeconds: Float? = null, val size: String? = null, val aspectRatio: String? = null, val providerOptions: Map<String, JsonElement> = emptyMap(), val headers: Map<String, String> = emptyMap(), val abortSignal: AbortSignal = AbortSignalNever, val seed: Int? = null, val fps: Int? = null, val resolution: String? = null)
Link copied to clipboard
interface VideoModel
Link copied to clipboard
data class VideoModelResult(val videos: List<GeneratedFile>, val warnings: List<CallWarning> = emptyList(), val response: LanguageModelResponseMetadata = LanguageModelResponseMetadata(), val providerMetadata: Map<String, JsonElement> = emptyMap())
Link copied to clipboard
class WireDecodeException(val provider: String, val operation: String, val path: String, message: String, val value: JsonElement? = null, cause: Throwable? = null) : AiSdkException

Properties

Link copied to clipboard

A signal that is never aborted. Useful as a default.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard

Global registry — upstream v7 registerTelemetry: register once at startup, all calls emit.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
val ContentPart.metadata: Map<String, JsonElement>?
val StreamEvent.metadata: Map<String, JsonElement>?

Functions

Link copied to clipboard

Bind an abort signal to a Job so the signal fires when the job completes (cancelled or otherwise). Lets a parent scope's lifetime automatically cancel anything observing the signal.

Link copied to clipboard
fun abortSignalFromJobs(vararg jobs: Job): AbortSignal
Link copied to clipboard
fun allOf(vararg conditions: StopCondition): StopCondition

Stop only when all conditions report done.

Link copied to clipboard
fun anyOf(vararg conditions: StopCondition): StopCondition

Stop when any of conditions reports done. v6's array-of-conditions shape.

Link copied to clipboard
fun CoroutineScope.asAbortSignal(): AbortSignal
Link copied to clipboard
fun <T> asArray(value: Iterable<T>): List<T>
Link copied to clipboard
fun <T> asSchema(schema: LazySchema<T>): Schema<T>
fun <T> asSchema(schema: Schema<T>?): Schema<T>
Link copied to clipboard
Link copied to clipboard
fun buildProviderOptions(block: ProviderOptionsBuilder.() -> Unit): Map<String, JsonElement>
Link copied to clipboard

Decode the inline base64 payload to bytes.

Link copied to clipboard

Like bytes but returns null for a URL-backed file instead of throwing.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
suspend fun convertToLanguageModelPrompt(messages: List<ModelMessage>, supportedUrls: Map<String, List<String>> = emptyMap(), download: DownloadFunction? = null): List<ModelMessage>

Resolve a prompt for a specific model — the port of upstream's convertToLanguageModelPrompt:

Link copied to clipboard
fun cosineSimilarity(left: List<Float>, right: List<Float>): Float
Link copied to clipboard
fun createGateway(settings: GatewayProviderSettings = GatewayProviderSettings()): GatewayProvider
Link copied to clipboard
fun createGatewayHttpProvider(client: HttpClient, settings: GatewayProviderSettings = GatewayProviderSettings(), json: Json = aiSdkJson): GatewayProvider
Link copied to clipboard
fun createGatewayProvider(settings: GatewayProviderSettings = GatewayProviderSettings()): GatewayProvider
Link copied to clipboard
fun createIdGenerator(prefix: String? = null, size: Int = 16, alphabet: String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator: String = "-", random: Random = Random.Default): IdGenerator
Link copied to clipboard
Link copied to clipboard
fun createMcpTransport(client: HttpClient, config: MCPTransportConfig): MCPTransport
Link copied to clipboard
fun createProviderRegistry(providers: Map<String, Provider>, defaultProviderId: String? = null, separator: String = ":", languageModelMiddleware: List<LanguageModelMiddleware> = emptyList()): ProviderRegistry
fun createProviderRegistry(vararg providers: Pair<String, Provider>, defaultProviderId: String? = null, separator: String = ":", languageModelMiddleware: List<LanguageModelMiddleware> = emptyList()): ProviderRegistry
Link copied to clipboard
fun <TInput, TContext> createProviderToolFactory(id: String, inputSerializer: KSerializer<TInput>, inputSchema: Schema<TInput>, description: String = "Provider tool "): ProviderToolFactory<TInput, TContext>
fun <TInput, TOutput, TContext> createProviderToolFactoryWithOutputSchema(id: String, inputSerializer: KSerializer<TInput>, inputSchema: Schema<TInput>, outputSerializer: KSerializer<TOutput>, outputSchema: Schema<TOutput>, supportsDeferredResults: Boolean = false, description: String = "Provider tool "): ProviderToolFactoryWithOutputSchema<TInput, TOutput, TContext>
Link copied to clipboard
fun createToolNameMapping(tools: List<LanguageModelTool> = emptyList(), providerToolNames: Map<String, String>, resolveProviderToolName: (LanguageModelTool) -> String?? = null): ToolNameMapping
Link copied to clipboard
fun customProvider(providerId: String, languageModels: Map<String, LanguageModel> = emptyMap(), embeddingModels: Map<String, EmbeddingModel> = emptyMap(), imageModels: Map<String, ImageModel> = emptyMap(), speechModels: Map<String, SpeechModel> = emptyMap(), transcriptionModels: Map<String, TranscriptionModel> = emptyMap(), rerankingModels: Map<String, RerankingModel> = emptyMap(), videoModels: Map<String, VideoModel> = emptyMap(), fallbackProvider: Provider? = null): Provider
Link copied to clipboard
inline fun <T> JsonElement.decodeAs(): T
fun <T> JsonElement.decodeAs(serializer: KSerializer<T>): T
Link copied to clipboard
inline fun <T> Map<String, JsonElement>?.decodeProviderMetadata(provider: String): T?
fun <T> Map<String, JsonElement>?.decodeProviderMetadata(provider: String, serializer: KSerializer<T>): T?
Link copied to clipboard
inline fun <T> Map<String, JsonElement>.decodeValue(name: String): T?
fun <T> Map<String, JsonElement>.decodeValue(name: String, serializer: KSerializer<T>): T?
Link copied to clipboard
fun defaultEmbeddingSettingsMiddleware(maxEmbeddingsPerCall: Int? = null, truncate: Boolean? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap()): EmbeddingModelMiddleware
Link copied to clipboard
fun detectMediaType(filename: String? = null, dataUrl: String? = null, explicit: String? = null): String?
Link copied to clipboard
fun devToolsMiddleware(recorder: DevToolsRecorder = InMemoryDevToolsRecorder(), environment: String = "development", runId: String = generateId(prefix = "run"), idGenerator: () -> String = { generateId(prefix = "step") }): LanguageModelMiddleware
Link copied to clipboard
fun <TContext> dynamicTool(name: String, description: String, inputSchemaJson: String = "{}", metadata: Map<String, JsonElement> = emptyMap(), toModelOutput: (JsonElement, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, executor: suspend ToolExecutionContext<TContext>.(JsonElement) -> JsonElement): Tool<JsonElement, JsonElement, TContext>

Runtime-typed tool equivalent to v6's dynamicTool. Inputs and outputs are raw JsonElement values, so the tool can be registered from external manifests or MCP-style runtime catalogs.

Link copied to clipboard

The effective approval ID — explicit PendingApproval.approvalId or fallback to PendingApproval.toolCallId.

Link copied to clipboard
suspend fun embed(model: EmbeddingModel, value: String, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, headers: Map<String, String> = emptyMap(), maxRetries: Int = 2): EmbedResult<String>
Link copied to clipboard
suspend fun embedMany(model: EmbeddingModel, values: List<String>, maxEmbeddingsPerCall: Int? = null, maxParallelCalls: Int = Int.MAX_VALUE, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, headers: Map<String, String> = emptyMap(), maxRetries: Int = 2): EmbedManyResult<String>
Link copied to clipboard
inline fun <T> encodeJsonElement(value: T): JsonElement
fun <T> encodeJsonElement(value: T, serializer: KSerializer<T>): JsonElement
Link copied to clipboard
Link copied to clipboard
suspend fun experimental_generateImage(model: ImageModel, prompt: String, n: Int = 1, size: String? = null, aspectRatio: String? = null, seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, files: List<ImageGenerationFile> = emptyList(), mask: ImageGenerationFile? = null): GenerateImageResult
Link copied to clipboard
suspend fun experimental_generateSpeech(model: SpeechModel, text: String, voice: String? = null, instructions: String? = null, speed: Float? = null, responseFormat: String? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever): GenerateSpeechResult
Link copied to clipboard
suspend fun experimental_generateVideo(model: VideoModel, prompt: String, n: Int = 1, image: GeneratedFile? = null, durationSeconds: Float? = null, size: String? = null, aspectRatio: String? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, seed: Int? = null, fps: Int? = null, resolution: String? = null): GenerateVideoResult
Link copied to clipboard
suspend fun experimental_transcribe(model: TranscriptionModel, audio: AudioSource, language: String? = null, prompt: String? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever): TranscribeResult
Link copied to clipboard
Link copied to clipboard
fun fixJson(input: String): String

Complete a partial/truncated JSON string so Json.parseToJsonElement can read it. Returns "" when nothing valid was scanned (e.g. a lone -). See parsePartialJson for the parse wrapper.

Link copied to clipboard
fun generatedFile(data: FileData, mediaType: String = data.mediaType ?: "application/octet-stream", filename: String? = data.filename, providerMetadata: Map<String, JsonElement> = emptyMap()): GeneratedFile
Link copied to clipboard
fun generateId(prefix: String? = null, random: Random = Random.Default): String
Link copied to clipboard
suspend fun generateImage(model: ImageModel, prompt: String, n: Int = 1, size: String? = null, aspectRatio: String? = null, seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, files: List<ImageGenerationFile> = emptyList(), mask: ImageGenerationFile? = null, logger: Logger = NoopLogger): GenerateImageResult
Link copied to clipboard
suspend fun <TOutput> generateObject(model: LanguageModel, output: Output<TOutput>, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text): GenerateObjectResult<TOutput>

Deprecated v6 compatibility helper. Prefer generateText with output = ...; this wrapper exists for call sites that still use the object-generation vocabulary.

Link copied to clipboard
suspend fun generateSpeech(model: SpeechModel, text: String, voice: String? = null, instructions: String? = null, speed: Float? = null, responseFormat: String? = null, language: String? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, logger: Logger = NoopLogger): GenerateSpeechResult
Link copied to clipboard
suspend fun generateText(model: LanguageModel, settings: CallSettings = CallSettings(), block: TextGenerationRequestBuilder.() -> Unit): GenerateTextResult<String>
suspend fun <TOutput> generateText(model: LanguageModel, output: Output<TOutput>, settings: CallSettings = CallSettings(), block: TextGenerationRequestBuilder.() -> Unit): GenerateTextResult<TOutput>
suspend fun generateText(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, settings: CallSettings): GenerateTextResult<String>
suspend fun <TOutput> generateText(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, output: Output<TOutput>, settings: CallSettings): GenerateTextResult<TOutput>
suspend fun <TOutput> generateText(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, output: Output<TOutput>, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text): GenerateTextResult<TOutput>

suspend fun generateText(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text): GenerateTextResult<String>

One-shot generation — invariant I-3, the only text entry point in v6.

Link copied to clipboard
suspend fun generateVideo(model: VideoModel, prompt: String, n: Int = 1, image: GeneratedFile? = null, durationSeconds: Float? = null, size: String? = null, aspectRatio: String? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, seed: Int? = null, fps: Int? = null, resolution: String? = null, logger: Logger = NoopLogger): GenerateVideoResult
Link copied to clipboard

Stop the moment the named tool is called in any step.

Link copied to clipboard
Link copied to clipboard
fun injectJsonInstruction(prompt: String? = null, schema: JsonElement? = null, schemaPrefix: String? = if (schema != null) DEFAULT_SCHEMA_PREFIX else null, schemaSuffix: String? = if (schema != null) DEFAULT_SCHEMA_SUFFIX else DEFAULT_GENERIC_SUFFIX): String

Build the JSON instruction block.

Link copied to clipboard
fun injectJsonInstructionIntoMessages(messages: List<ModelMessage>, schema: JsonElement? = null, schemaPrefix: String? = if (schema != null) DEFAULT_SCHEMA_PREFIX else null, schemaSuffix: String? = if (schema != null) DEFAULT_SCHEMA_SUFFIX else DEFAULT_GENERIC_SUFFIX): List<ModelMessage>

Splice injectJsonInstruction into a message list's system prompt.

Link copied to clipboard
suspend fun isLoopFinished(state: LoopState, stopWhen: StopCondition): Boolean

Consolidated check: would the loop terminate after this state?

Link copied to clipboard
fun isUrlSupported(mediaType: String, url: String, supportedUrls: Map<String, List<Regex>>): Boolean
Link copied to clipboard
fun <T> jsonSchema(schema: JsonElement, validate: (JsonElement) -> T? = null): Schema<T>
Link copied to clipboard
fun langChainToUIMessageStream(stream: Flow<LangChainStreamItem>, callbacks: StreamCallbacks? = null, assistantMessageId: String = "langchain-msg-1"): Flow<UIMessage>
Link copied to clipboard
fun <T> lazySchema(createSchema: () -> Schema<T>): LazySchema<T>
Link copied to clipboard
fun llamaIndexToUIMessageStream(stream: Flow<LlamaIndexEngineResponse>, callbacks: StreamCallbacks? = null, assistantMessageId: String = "1"): Flow<UIMessage>
Link copied to clipboard
fun maybeSignToolApproval(secret: ByteArray?, approvalId: String, toolCallId: String, toolName: String, input: JsonElement): String?

Sign when a secret is configured; null otherwise (upstream maybeSignApproval).

Link copied to clipboard
Link copied to clipboard
fun modelId(value: String): ModelId
Link copied to clipboard
fun modelRef(value: String): ModelRef
fun modelRef(providerId: ProviderId, modelId: ModelId): ModelRef
fun modelRef(providerId: String, modelId: String): ModelRef
Link copied to clipboard

Stock self-healing repair: re-prompt the model with the tool's JSON schema + the failed args + the parse error, asking for corrected JSON. If the second response parses cleanly, return a ContentPart.ToolCall with the corrected input; otherwise return null (the agent loop surfaces StreamEvent.ToolError).

Link copied to clipboard
fun <T> outputArray(elementSerializer: KSerializer<T>, name: String = elementSerializer.descriptor.serialName.substringAfterLast('.') + "[]", description: String? = null): Output<List<T>>
Link copied to clipboard
fun outputChoice(options: Iterable<String>, name: String = "choice", description: String? = null): Output<String>
fun outputChoice(vararg options: String, name: String = "choice", description: String? = null): Output<String>
fun <T> outputChoice(options: Iterable<T>, encode: (T) -> String, decodeChoice: (String) -> T, name: String = "choice", description: String? = null): Output<T>
Link copied to clipboard
fun outputJson(name: String = "json", description: String? = null): Output<JsonElement>
Link copied to clipboard
fun <T> outputObj(serializer: KSerializer<T>, name: String = serializer.descriptor.serialName.substringAfterLast('.'), description: String? = null): Output<T>
Link copied to clipboard
fun <T> parseJsonEventStream(chunks: Flow<String>, schema: Schema<T>, json: Json = Json): Flow<ParseResult<T>>
Link copied to clipboard

Parse possibly-partial JSON. Mirrors Vercel AI SDK v6 parsePartialJson:

Link copied to clipboard
fun <T> parseProviderOptions(provider: String, providerOptions: Map<String, JsonElement>, schema: Schema<T>): T?
Link copied to clipboard
operator fun Usage.plus(other: Usage): Usage
Link copied to clipboard
Link copied to clipboard
fun <TInput, TOutput, TContext> providerExecutedTool(name: String, description: String, inputSerializer: KSerializer<TInput>, outputSerializer: KSerializer<TOutput>, metadata: Map<String, JsonElement> = emptyMap()): Tool<TInput, TOutput, TContext>
Link copied to clipboard
Link copied to clipboard
fun Map<String, JsonElement>?.providerMetadata(provider: String): JsonElement?
Link copied to clipboard
inline fun <T> ContentPart.providerMetadataAs(provider: String): T?
inline fun <T> GenerateObjectResult<*>.providerMetadataAs(provider: String): T?
inline fun <T> GenerateTextResult<*>.providerMetadataAs(provider: String): T?
inline fun <T> LanguageModelResult.providerMetadataAs(provider: String): T?
inline fun <T> StreamEvent.providerMetadataAs(provider: String): T?
fun <T> ContentPart.providerMetadataAs(provider: String, serializer: KSerializer<T>): T?
fun <T> GenerateObjectResult<*>.providerMetadataAs(provider: String, serializer: KSerializer<T>): T?
fun <T> GenerateTextResult<*>.providerMetadataAs(provider: String, serializer: KSerializer<T>): T?
fun <T> LanguageModelResult.providerMetadataAs(provider: String, serializer: KSerializer<T>): T?
fun <T> StreamEvent.providerMetadataAs(provider: String, serializer: KSerializer<T>): T?
Link copied to clipboard
fun pruneMessages(messages: List<ModelMessage>, reasoning: PruneReasoning = PruneReasoning.None, toolCalls: PruneToolCalls = PruneToolCalls.None, emptyMessages: PruneEmptyMessages = PruneEmptyMessages.Remove): List<ModelMessage>
Link copied to clipboard
inline fun <T> JsonObjectBuilder.putJson(name: String, value: T)
fun <T> JsonObjectBuilder.putJson(name: String, value: T, serializer: KSerializer<T>)
Link copied to clipboard
inline fun <T> JsonObjectBuilder.putJsonIfNotNull(name: String, value: T?)
fun <T> JsonObjectBuilder.putJsonIfNotNull(name: String, value: T?, serializer: KSerializer<T>)
Link copied to clipboard
fun registerTelemetry(integration: Telemetry)
Link copied to clipboard

Stop when the model has emitted the same (toolName, input) tuple n consecutive steps in a row — i.e. the loop is spinning on a tool whose result didn't change the model's behavior. Documented anti-pattern for small / on-device models that can't reason their way out of an unhelpful tool result; surfaced as a hard stop so the host renders the trapped state instead of looping until the step cap.

Link copied to clipboard
suspend fun rerank(model: RerankingModel, query: String, documents: List<String>, topN: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, maxRetries: Int = 2): RerankResult<String>
Link copied to clipboard
suspend fun <T> retryWithExponentialBackoff(policy: RetryPolicy = RetryPolicy(), shouldRetry: (Throwable) -> Boolean = { true }, block: suspend (attempt: Int) -> T): T

Retry block with exponential backoff, honoring server Retry-After headers, and surfacing the full attempt history as a RetryError on exhaustion — the contract upstream's retryWithExponentialBackoff exposes.

Link copied to clipboard
fun <T> safeValidateTypes(value: JsonElement, schema: LazySchema<T>, context: TypeValidationContext? = null): ValidationResult<T>
fun <T> safeValidateTypes(value: JsonElement, schema: Schema<T>, context: TypeValidationContext? = null): ValidationResult<T>
Link copied to clipboard
fun <TContext, TOutput> Agent<TContext, TOutput>.session(scope: CoroutineScope, initialMessages: List<ModelMessage> = emptyList()): AgentSession<TContext, TOutput>
Link copied to clipboard
fun signToolApproval(secret: ByteArray, approvalId: String, toolCallId: String, toolName: String, input: JsonElement): String

Sign one approval request. approvalId is the EFFECTIVE id (explicit approvalId ?: toolCallId).

Link copied to clipboard
fun simulateReadableStream(events: List<StreamEvent>, initialDelayMs: Long = 0, chunkDelayMs: Long = 10): Flow<StreamEvent>

Replay a recorded list of StreamEvents as a fresh cold Flow with configurable inter-chunk delay. Foundation for the caching middleware pattern: cache stream parts as List<StreamEvent>, on cache hit replay via simulateReadableStream so the stream contract is preserved.

Link copied to clipboard
fun smoothStream(upstream: Flow<StreamEvent>, delayMs: Long = 10, chunkBy: ChunkBy = ChunkBy.Word): Flow<StreamEvent>
Link copied to clipboard
Link copied to clipboard
fun splitDataUrl(dataUrl: String): DataUrl
Link copied to clipboard
fun splitProviderModelId(modelId: String, separator: String = ":"): Pair<String?, String>
Link copied to clipboard

Stop after n completed steps. v6's default is 20 if stopWhen omitted.

Link copied to clipboard
inline fun <TInput, TOutput, TContext> streamingTool(name: String, description: String, noinline needsApproval: suspend (input: TInput, options: ToolPredicateOptions<TContext>) -> Boolean? = null, noinline toModelOutput: (TOutput, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, strict: Boolean = true, inputExamples: List<String> = emptyList(), noinline onInputStart: suspend (streamingId: String) -> Unit? = null, noinline onInputDelta: suspend (streamingId: String, delta: String) -> Unit? = null, noinline onInputAvailable: suspend (toolCallId: String, input: TInput) -> Unit? = null, metadata: Map<String, JsonElement> = emptyMap(), providerExecuted: Boolean = false, noinline executor: ToolExecutionContext<TContext>.(TInput) -> Flow<TOutput>): Tool<TInput, TOutput, TContext>

fun <TInput, TOutput, TContext> streamingTool(name: String, description: String, inputSerializer: KSerializer<TInput>, outputSerializer: KSerializer<TOutput>, needsApproval: suspend (input: TInput, options: ToolPredicateOptions<TContext>) -> Boolean? = null, toModelOutput: (TOutput, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, strict: Boolean = true, inputExamples: List<String> = emptyList(), onInputStart: suspend (streamingId: String) -> Unit? = null, onInputDelta: suspend (streamingId: String, delta: String) -> Unit? = null, onInputAvailable: suspend (toolCallId: String, input: TInput) -> Unit? = null, metadata: Map<String, JsonElement> = emptyMap(), providerExecuted: Boolean = false, executor: ToolExecutionContext<TContext>.(TInput) -> Flow<TOutput>): Tool<TInput, TOutput, TContext>

Top-level factory for Tool with a Flow-returning executor. Each emission lands as a StreamEvent.ToolResult; the LAST emission is the final tool result that feeds the model on subsequent turns, and all earlier emissions are surfaced as ToolResult(preliminary = true) for UI consumption only.

Link copied to clipboard
fun <TOutput> streamObject(model: LanguageModel, output: Output<TOutput>, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text): Flow<StreamEvent>

Deprecated v6 compatibility helper. Prefer streamText with output = ...; the KMP core streams typed StreamEvent values instead of returning a browser/Node stream facade.

Link copied to clipboard
fun <TOutput> streamObjectResult(model: LanguageModel, output: Output<TOutput>, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text, repairText: (String) -> String?? = null): StreamObjectResult<TOutput>

Stream a structured object, returning a typed StreamObjectResult — the v6 streamObject surface (the older streamObject returns a raw event flow and is deprecated). Use StreamObjectResult.partialObjectStream for incremental UI or StreamObjectResult.objectValue for the final value.

Link copied to clipboard
fun streamText(model: LanguageModel, settings: CallSettings = CallSettings(), block: TextGenerationRequestBuilder.() -> Unit): Flow<StreamEvent>

fun streamText(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, output: Output<*>? = null, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text): Flow<StreamEvent>

Streaming generation — invariant I-3. Returns a cold Flow that drives one upstream call when collected. For tool-loop agents, use Agent.stream instead.

Link copied to clipboard
fun streamTextResult(model: LanguageModel, settings: CallSettings = CallSettings(), block: TextGenerationRequestBuilder.() -> Unit): StreamTextResult
fun streamTextResult(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, settings: CallSettings): StreamTextResult
fun streamTextResult(model: LanguageModel, prompt: String? = null, messages: List<ModelMessage> = emptyList(), system: String? = null, temperature: Float? = null, topP: Float? = null, topK: Int? = null, maxOutputTokens: Int? = null, stopSequences: List<String> = emptyList(), seed: Int? = null, providerOptions: Map<String, JsonElement> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, output: Output<*>? = null, presencePenalty: Float? = null, frequencyPenalty: Float? = null, responseFormat: ResponseFormat = ResponseFormat.Text): StreamTextResult
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
fun ToolResultOutput.toJsonElement(): JsonElement
Link copied to clipboard
inline fun <TInput, TOutput, TContext> tool(name: String, description: String, noinline needsApproval: suspend (input: TInput, options: ToolPredicateOptions<TContext>) -> Boolean? = null, noinline toModelOutput: (TOutput, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, strict: Boolean = true, inputExamples: List<String> = emptyList(), noinline onInputStart: suspend (streamingId: String) -> Unit? = null, noinline onInputDelta: suspend (streamingId: String, delta: String) -> Unit? = null, noinline onInputAvailable: suspend (toolCallId: String, input: TInput) -> Unit? = null, metadata: Map<String, JsonElement> = emptyMap(), providerExecuted: Boolean = false, noinline executor: suspend ToolExecutionContext<TContext>.(TInput) -> TOutput): Tool<TInput, TOutput, TContext>

fun <TInput, TOutput, TContext> tool(name: String, description: String, inputSerializer: KSerializer<TInput>, outputSerializer: KSerializer<TOutput>, needsApproval: suspend (input: TInput, options: ToolPredicateOptions<TContext>) -> Boolean? = null, toModelOutput: (TOutput, ToolPredicateOptions<TContext>) -> ToolResultOutput? = null, strict: Boolean = true, inputExamples: List<String> = emptyList(), onInputStart: suspend (streamingId: String) -> Unit? = null, onInputDelta: suspend (streamingId: String, delta: String) -> Unit? = null, onInputAvailable: suspend (toolCallId: String, input: TInput) -> Unit? = null, metadata: Map<String, JsonElement> = emptyMap(), providerExecuted: Boolean = false, providerOptions: Map<String, JsonElement> = emptyMap(), executor: suspend ToolExecutionContext<TContext>.(TInput) -> TOutput): Tool<TInput, TOutput, TContext>

Top-level factory for Tool with a single-value executor. Mirrors v6's tool({...}) ergonomics in an idiomatic common Kotlin shape.

Link copied to clipboard
fun toolApprovalResponseMessage(toolCallId: String, approved: Boolean, reason: String? = null, approvalId: String? = null): ModelMessage
Link copied to clipboard
fun toolMessage(toolCallId: String, toolName: String, output: JsonElement): ModelMessage
Link copied to clipboard
Link copied to clipboard
fun <TContext> toolSetOf(vararg tools: Tool<*, *, TContext>): ToolSet<TContext>

Construct a ToolSet from individual tools. Throws on duplicate names.

Link copied to clipboard
@JvmName(name = "langChainToUIMessageStreamExport")
fun toUIMessageStream(stream: Flow<LangChainStreamItem>, callbacks: StreamCallbacks? = null, assistantMessageId: String = "langchain-msg-1"): Flow<UIMessage>
fun toUIMessageStream(stream: Flow<LlamaIndexEngineResponse>, callbacks: StreamCallbacks? = null, assistantMessageId: String = "1"): Flow<UIMessage>
Link copied to clipboard
suspend fun transcribe(model: TranscriptionModel, audio: AudioSource, language: String? = null, prompt: String? = null, providerOptions: Map<String, JsonElement> = emptyMap(), headers: Map<String, String> = emptyMap(), abortSignal: AbortSignal = AbortSignalNever, logger: Logger = NoopLogger): TranscribeResult
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
fun <T> validateTypes(value: JsonElement, schema: LazySchema<T>, context: TypeValidationContext? = null): T
fun <T> validateTypes(value: JsonElement, schema: Schema<T>, context: TypeValidationContext? = null): T
Link copied to clipboard
fun verifyToolApprovalSignature(secret: ByteArray, signature: String, approvalId: String, toolCallId: String, toolName: String, input: JsonElement): Boolean

Verify a replayed approval's signature. Constant-time comparison; false on any malformed input.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard

Compose middlewares over model into a new LanguageModel. Order: the first middleware in the list is the outermost wrapper — wrapGenerate runs first on the way in, last on the way out (innermost in the call stack, like Express middleware).

Link copied to clipboard
fun wrapProvider(provider: Provider, middleware: ProviderMiddleware): Provider